package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //1.查出所有分类

        //2.组装成父子的树形结构
        //2.1找所有有一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
           categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren( getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) ->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    /**
     * 递归查找 每一个菜单的子菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root ,List<CategoryEntity> entities){
        List<CategoryEntity> childrens = entities.stream().filter( menu -> {
            return menu.getParentCid().equals(root.getCatId());
        }).map( menu ->{
            menu.setChildren( getChildrens( menu, entities));
            return menu;
        }).sorted( (menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return childrens;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1. 检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //返回分类id的数组：[2, 25, 55]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        //收集当前分类id，及其所有的父id(如果有的话)
        List<Long> parentPath = findParentPath(catelogId, paths);

        //将分类id进行逆序，如：225, 25, 2  ->   2, 25, 255
        Collections.reverse(parentPath);
        return paths.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新关联的数据：例如 pms_category_brand_relation
     * @param category 分类
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        //1.更新级联关系表
        //1.1 更新pms_category_brand_relation
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

        //TODO 更新其他关联表
    }

    //225, 25, 2
    private List<Long> findParentPath(Long catelogId, List<Long> paths){
        //1.收集当前节点的id
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        if (parentCid != 0L){
            findParentPath(parentCid, paths);
        }
        return paths;
    }

}